#!/usr/bin/perl -w
#除了这个脚本以外，要想清除android sdk文档中google相关的js代码，还需在docs.js中删除添加plusone的代码。
use strict;
use utf8;

use HTML::TreeBuilder;
use HTML::Element;

foreach my $file (@ARGV) {
  my $root = HTML::TreeBuilder->new_from_file($file);

  #delete css fonts reference
  my $cssfonts = $root -> look_down( _tag => "link",
		    href => qr/^(http:)?\/\/fonts\.googleapis\.com\/.*/);
  if ($cssfonts) {
    print "$file: fonts.googleapis.com link detected. Delete.\n";
    $cssfonts -> delete;
  }
  
  #delete google jsapi
  #<script src="http://www.google.com/jsapi" type="text/javascript"></script>
  my $jsapi = $root -> look_down ( _tag => "script",
		       src => qr/^http:\/\/www\.google\.com\/jsapi/ );
  if ($jsapi) {
    print "$file: jsapi script element detected. Delete.\n";
    $jsapi -> delete;
  }

  my $ytblogger = $root -> look_down ( _tag => "script",
				       src => qr/^https:\/\/developer\.android\.com\/ytblogger_lists_unified\.js/
				     );
  if ($ytblogger) {
    print "$file: ytblogger script element detected. Delete.\n";
    $ytblogger -> delete;
  }
  
  #delete google-analytics js node
  my $analytics = $root -> look_down ( _tag => "script",
				       sub {
					 my @contents = $_[0]->content_list;
					 grep $_ =~ m/.*\.google-analytics\.com\/.*\.js.*/ , @contents;
#					 @contents ? $contents[0] =~ m/.*\.google-analytics\.com\/ga\.js.*/ : 0 ;
				       }
				     );
  if ($analytics) {
    print "$file: google anaytics script element detected. Delete.\n";
    $analytics -> delete;
  }

  open CLEAN_HTML, ">${file}.clean";
  print CLEAN_HTML $root->as_HTML;
  close CLEAN_HTML;
  unlink $file or warn "Could not unlink $file.";
  rename "${file}.clean",$file;
}
